﻿using Microsoft.AspNetCore.Authorization;
using RBACDemo.Ability.Docking.RoleAuthApp;
using RBACDemo.Ability.Docking.RoleAuthApp.Dtos;
using RBACDemo.Domain.Managers;
using RBACDemo.Domain.UserInfo;
using Youshow.Ace.Ability;
using Youshow.Ace.Ability.Dtos;
using Youshow.Ace.AspNetCore.ApiRouteDescription;
using Youshow.Ace.AspNetCore.ApiRouteDescription.Models;
using Youshow.Ace.AspNetCore.Jwt;

namespace RBACDemo.Ability.RoleAuthApp;

[Authorize(AceJwtPolicyDefault.AUTHORIZATION_POLICY)]
public class RoleAuthService(
    RoleAuthManager roleAuthManager,
    IAceApiRouteDescriptor aceApiRouteDescriptor) : AutoAbilityServicer<Role,RoleDto,long,PageSortRequestDto,RoleCreateDto,RoleUpdateDto>,IRoleAuthService
{
    /// <summary>
    ///  根据项目中的Service和Controller信息去对ApiAuth表中的数据进行CUD
    /// </summary>
    public async Task RefreshApiAuthAsync()
    {
        var models = aceApiRouteDescriptor.GetApiRouteDescriptions();
        var apiAuths = ModelMapper.Map<List<ApiRouteDescriptionModel>, List<ApiAuth>>(models);
        await roleAuthManager.AddApiAuthAsync(apiAuths);
    }

    /// <summary>
    ///  roleId、apiAuthIds给角色添加相应的权限，保存在RoleApiAuthMapping表中
    /// </summary>
    /// <param name="roleId">角色Id</param>
    /// <param name="apiAuthIds">权限Id集合</param>
    public async Task AddRoleApiAuthsAsync(long roleId, params long[] apiAuthIds)
    {
        await roleAuthManager.DeleteRoleApiAuthAsync(roleId);
        await roleAuthManager.AddRoleApiAuthAsync(roleId, apiAuthIds.ToList());
    }
}